library(metafor)
library(tidyverse)
library(showtext)
library(magrittr)
library(shadowtext)
library(broom)


"https://github.com/thomasjwood/cgptw22/raw/main/" %>% 
  str_c(
    c("cates_w1_all_adj",
      "treatments_df",
      "diff_in_cates_w1_all_adj"),
      ".rds"
    ) %>% 
  map2(
    str_c("t", 0:2),
    \(i, j)

    i %>%
      url %>% 
      gzcon %>% 
      readRDS %>% 
      assign(
       x =  j,
        envir = .GlobalEnv
        )
  )



t0 %<>% 
  left_join(
    t1 %>% 
      select(fc, panel, topic_short_2, congeniality)
  ) %>% 
  mutate(
    congeniality = congeniality %>% 
      str_wrap(15) %>% 
      fct_inorder,
    congeniality = congeniality %>% 
      fct_rev,
    lab = estimate %>%
      round(1) %>% 
      as.character,
    lab = lab %>% 
      str_extract("\\d") %>% 
      equals("0") %>% 
      ifelse(
        lab %>% 
          str_replace("\\d", ""),
        lab
      )
    )

t0$topic_short_2 %<>%
  factor(
    t0 %>%
      filter(
        term %>%
          str_detect("control", negate = T)
        ) %>%
      group_by(congeniality, topic_short_2) %>%
      summarize(
        mu = estimate %>%  mean
      ) %>%
      arrange(desc(congeniality), desc(mu)) %>% 
      use_series(topic_short_2)
    )

t0$type <- case_when(
  t0$term %>% 
    str_detect("control") ~ "Misinformation effect",
  t0$term %>% 
    str_detect("factcheck") ~ "Correction effect"
  ) %>% 
  factor(
    c("Misinformation effect",
      "Correction effect")
  )

t0$pg <- t0$p.value %>% 
  is_less_than(0.05) %>% 
  ifelse(
    "sig", "insig"
  )

# significance of party effect differences

t2 %<>% 
  filter(
    p.value %>% 
      is_less_than(.05)
  ) %>% 
  mutate(
    type = term %>% 
      str_detect("control") %>% 
      ifelse(
        "Misinformation effect",
        "Correction effect"
        )
    ) %>% 
  left_join(
    t0 %>% 
      ungroup %>% 
      select(topic_short_2, congeniality) %>% 
      distinct
    ) %>% 
  left_join(
    t0 %>% 
      ungroup %>% 
      select(topic_short_2, term, type, estimate) %>% 
      group_by(topic_short_2, term, type) %>% 
      summarize(
        lo = estimate %>% min,
        hi = estimate %>% max
        ) %>% 
      ungroup %>% 
      select(-term)
    ) %>% 
  mutate(
    lab = 
      c("***", "**", "*", "") %>%
      extract(
        p.value %>%
          findInterval(
            c(-Inf, .001, .01, .05, Inf)
            )
        ),
    mid = lo %>% 
      add(hi) %>% 
      divide_by(2)
    )

# yints for adjusted row facets

t2$yint <- t2$congeniality %>%
  equals(
    "False claim\ncongenial to\nRepublicans"
  ) %>%
  ifelse(-10, -0)

t2$topic_short_2 %<>%
  factor(
    t0$topic_short_2 %>% 
      levels
  )

t2$type %<>%
  factor(
    t0$type %>% 
      levels
    )



# add meta analytic summaries
t0_2 <- t0 %>% 
  ungroup %>% 
  group_by(
    congeniality, lucid_pid_3, term
  ) %>% 
  nest %>% 
  mutate(
    mm = data %>% 
      map(
      \(i)
      rma.uni(
        yi = estimate, 
        sei = std.error, 
        data = i
      )
    )
  ) %>% 
  select(-data) %>% 
  ungroup %>% 
  pmap_dfr(
    \(lucid_pid_3, term, congeniality, mm)
    
    mm %>% 
      tidy(conf.int = T) %>% 
      select(-term, -type) %>% 
      mutate(
        lucid_pid_3, term, congeniality
      )
    ) %>% 
  mutate(
    topic_short_2 = "Overall" %>% 
      factor(
        c(
          "Overall",
          " ",
          t0$topic_short_2 %>%
            levels
          )
        ), 
    type = term %>% 
      str_detect("control") %>% 
      ifelse(
        "Misinformation effect",
        "Correction effect"
      ) %>% 
      factor(
        t0$type %>% 
          levels
        ),
    pg = p.value %>% 
      is_less_than(0.05) %>% 
      ifelse(
        "sig", "insig"
        ),
    lab = estimate %>%
      round(1) %>% 
      as.character,
    ) %>% 
  bind_rows(
    t0 %>% 
      mutate(
        topic_short_2 = topic_short_2 %>% 
          factor(
            c(
              "Overall",
              " ",
              t0$topic_short_2 %>%
                levels
            )
          )
        )
    )

t2$topic_short_2 %<>%
  factor(
    t0_2$topic_short_2 %>% 
      levels
  )

t0_2 %>% 
  ggplot() +
  geom_vline(
    aes(xintercept = xint),
    data = t0_2 %>% 
      mutate(xint = 0),
    size = .25,
    linetype = "dashed"
  ) +
  geom_blank(
    aes(
      estimate, y = topic_short_2
    ),
    size = 0,
    data = t0_2 %>% 
      bind_rows(
        tribble(
          ~estimate, ~topic_short_2, ~type, ~congeniality,
          1, " ", "Misinformation effect", "False claim\ncongenial to\nRepublicans",
          1, " ", "Misinformation effect", "False claim\ncongenial to\nDemocrats"
          ) %>% 
          mutate(
            topic_short_2 = topic_short_2 %>% 
              factor(
                t0_2$topic_short_2 %>% 
                  levels
              ),
            type = type %>% 
              factor(
                t0_2$type %>% 
                  levels
                ),
            congeniality = congeniality %>% 
              factor(
                t0_2$congeniality %>% 
                  levels
              )
            )
      )
    ) +
  # 95% confidence intervals
  geom_linerange(
    aes(
      xmin = conf.low %>% 
        add(
          type %>% 
            str_detect("Correction") %>% 
            ifelse(-.075, .075)
          ),
      xmax = conf.high %>% 
        add(
          type %>% 
            str_detect("Correction") %>% 
            ifelse(.075, -.075)
          ),
      group = lucid_pid_3, 
      y = topic_short_2,
    ),
    color = "black",
    size = .75,
    position = position_dodge(.65/4),
    data = t0_2
  ) +
  geom_linerange(
    aes(
      xmin = conf.low,
      xmax = conf.high,
      color = lucid_pid_3, 
      y = topic_short_2,
    ),
    position = position_dodge(.65/4),
    data = t0_2
    ) +
  geom_label(
    aes(
      x,
      label = lab, fill = lucid_pid_3,
      group = lucid_pid_3,
      y = 16,
    ),
    position = position_dodge(width = 2),
    size = 2.5,
    color = "black",
    fontface = "italic",
    data =  tribble(
      ~x,   ~lab,
      -6,   "Democrats",
      18, "Republicans"
    ) %>%
      mutate(
        lucid_pid_3  = c(
          "Democrat",
          "Republican") %>%
          factor(
            c("Democrat",
              "Republican")
          ),
        type = "Misinformation effect" %>%
          factor(
            t0_2$type %>%
              levels
          ),
        congeniality = t0_2$congeniality %>%
          levels %>%
          extract2(1) %>%
          factor(
            t0_2$congeniality %>%
              levels
          )
      )
  ) +
  geom_segment(
    aes(
      x = lo, xend = hi,
      y = topic_short_2 %>% as.numeric %>% add(yint) %>% add(.5),
      yend = topic_short_2 %>% as.numeric %>% add(yint) %>% add(.5)
    ),
    data = t2,
    size = .25,
    linetype = "dotted"
  )  +
  geom_segment(
    aes(
      x = lo, xend = lo,
      y = topic_short_2 %>% as.numeric %>% add(yint),
      yend = topic_short_2 %>% as.numeric %>% add(yint) %>% add(.5)
    ),
    data = t2,
    size = .25,
    linetype = "dotted"
  )  +
  geom_segment(
    aes(
      x = hi, xend = hi,
      y = topic_short_2 %>% as.numeric %>% add(yint),
      # add(yint) %>% add(.5),
      yend = topic_short_2 %>% as.numeric %>% add(yint) %>% add(.5)
    ),
    data = t2,
    size = .25,
    linetype = "dotted"
  )  +
  geom_label(
    aes(
      x = mid, label = lab,
      y = topic_short_2 %>%
        as.numeric %>%
        add(.41) %>% 
        add(yint)
      ),
    data = t2,
    fill = "grey95",
    label.size = 0,
    fontface = "bold",
    size = 3,
    label.padding = unit(0.125, "lines")
  ) +
  geom_point(
    aes(
      estimate, topic_short_2,
      fill = lucid_pid_3,
      group = lucid_pid_3, 
      size = pg
    ),
    # size = 7,
    shape = 21,
    color = "black",
    position = position_dodge(.65/4),
    data = t0_2
    ) +
  geom_text(
    aes(
      estimate, topic_short_2, 
      label = lab,
      group = lucid_pid_3
    ),
    size = 1.75,
    color = "black",
    position = position_nudge(y = .16/4),
    data = t0_2 %>% 
      filter(
        p.value < .05 &
        lucid_pid_3 == "Republican"
      )
  ) +
  geom_text(
    aes(
      estimate, topic_short_2, 
      label = lab,
      group = lucid_pid_3
    ),
    size = 1.75,
    color = "black",
    position = position_nudge(y = -.16/4),
    data = t0_2 %>% 
      filter(
        p.value < .05 &
        lucid_pid_3 != "Republican"
        )
    ) +
  facet_grid(
    congeniality ~ type, 
    scales = "free", 
    space = "free", 
    drop = T
  ) +
  labs(x = "", y = "") +
  scale_size_manual(values = c(3, 6)) +
  scale_fill_manual(
    values = c("grey99",
               "grey65") %>% 
      rev
  ) +
  scale_color_manual(
    values = c("grey80",
               "grey65") %>% 
      rev
  ) +
  scale_y_discrete(
    breaks = t0_2$topic_short_2 %>%
      levels, 
    drop =  T
  ) 